;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.Plan", [])
        .controller("PlanCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "UserContextService", "$timeout", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, UserContextService, $timeout) {
            var btnPermissionCode = {
                purchasePlanAdd: window.ActionCode.purchasePlanAdd,
                purchasePlanEdit: window.ActionCode.purchasePlanEdit,
                purchasePlanDel: window.ActionCode.purchasePlanDel,
                purchasePlanAudit: window.ActionCode.purchasePlanAudit,
                purchasePlanManualFinish: window.ActionCode.purchasePlanManualFinish
            };
            var tabFlag = {
                0: "采购计划详情",
                1: "新增采购计划",
                2: "编辑采购计划"
            };

            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.tabFlag = {};
            $scope.btnPermission = {
                purchasePlanAdd: true,
                purchasePlanEdit: true,
                purchasePlanDel: true,
                purchasePlanAudit: true,
                purchasePlanManualFinish: true
            };
            $scope.markInfo = {
                allCheckedBill: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.exportParam = {
                sectionParam: {
                    ids: [],
                    rejectSumIds: []
                },
                sectionUrl: ybHttp.RequestUrl("device", "/buyPlan/export"),
                allUrl: ybHttp.RequestUrl("device", "/buyPlan/exportAll"),
                rejectSumSectionUrl: ybHttp.RequestUrl("device", "/buyPlan/rejectSumExport"),
                rejectSumAllUrl: ybHttp.RequestUrl("device", "/buyPlan/rejectSumExportAll"),
            };
            $scope.condition = {};
            $scope.dataList = [];
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                AdvanceSearchAdd: false,
                AdvanceSearchLackAdd: false,
            };
            $scope.tableConfig = {
                fixedWidth: 200,
                scrollWidth: 1250,
                tableCol: [
                    {
                        type: "",
                        name: "采购计划单号",
                        dataField: "planOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "createName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请部门",
                        dataField: "deptName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "purchaseType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "note",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "auditStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditNote",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建采购单状态",
                        dataField: "sendStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 160,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.auditStatusList = [{
                    code: 0,
                    name: "待审核"
                },
                {
                    code: 1,
                    name: "审核通过"
                },
                {
                    code: 2,
                    name: "审核拒绝"
                }
            ];
            $scope.sendStatusList = [{
                    code: 0,
                    name: "未创建"
                },
                {
                    code: 1,
                    name: "部分创建"
                },
                {
                    code: 2,
                    name: "已创建"
                }
            ];

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.buyPlan.submitted = false;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        $scope.tabFlag.type = 1;
                        $scope.tabFlag.name = tabFlag[1];
                        break;
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        break;
                    case 6:
                        break;                        
                    default:
                        break;
                }
            };

            $scope.addPlan = function (type) {
                $scope.buyPlan.formInfo.headerInfo.stockOutFlag = type
                $scope.buyPlan.formInfo.materialList = [];
                setCurUserInfo4buyPlan();
                if (type == 0) {
                    $scope.materiels.setFixedWidth();
                    getMaterielList(1);
                    $scope.changeTab(1);
                } else if (type == 1) {
                    $scope.setFixedWidthLack();
                    getMaterielListLack(1);
                    $scope.changeTab(5);
                } else if (type == 2) {
                    ybWidget.GetTableCol($scope.lackCollectTableConfig.tableCol, 'unsalableNum').isShow = true;
                    $scope.changeTab(6);
                    $scope.setFixedWidthLack();
                    $scope.curUrl4AllListLack = "/buyPlan/listBukuSumInfo";
                    getMaterielAllListLack(1);
                } else if (type == 3) {
                    ybWidget.GetTableCol($scope.lackCollectTableConfig.tableCol, 'unsalableNum').isShow = false;
                    $scope.changeTab(7);
                    $scope.setFixedWidthLack();
                    $scope.curUrl4AllListLack = "/buyPlan/listJinjiSumInfo";
                    getMaterielAllListLack(1);
                }
            };

            function setCurUserInfo4buyPlan() {
                $scope.buyPlan.formInfo.headerInfo.createName = $scope.curUser.name;
                $scope.buyPlan.formInfo.headerInfo.deptId = $scope.curUser.deptId;
                $scope.buyPlan.formInfo.headerInfo.deptName = $scope.curUser.deptName;
            }

            $scope.editPlan = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.buyPlan.formInfo = data;
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.changeTab(2);
                });
            };

            $scope.auditPlan = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.buyPlan.formInfo = data;
                    $scope.changeTab(3);
                });
            };

            $scope.delPlan = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/buyPlan/remove";
                    ybHttp.Post(service, reqUrl, [item.id]).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.manualFinish = function (id, code) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/buyPlan/manualFinish";
                    var param = {
                        id: id,
                        materialsNo: code
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!code) {
                            getDataList();
                        } else {
                            viewDetail({
                                id: id
                            })
                        }
                    });
                })
            };

            $scope.nextStep = function () {
                $scope.buyPlan.formInfo.headerInfo.createDate = +new Date();

                const stockOutType = $scope.buyPlan.formInfo.headerInfo.stockOutFlag;
                if (stockOutType == 1 || stockOutType == 2 || stockOutType == 3) {
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1]
                }
                if (stockOutType == 1) { // 缺货新增
                    // 合并相同零件信息(qty取同一零件缺货数量之和)
                    const groups = {};
                    $scope.buyPlan.formInfo.materialList.forEach(g => {
                        const groupId = 'g' + g.materialsNo
                        groups[groupId] = groups[groupId] || []
                        groups[groupId].push(g)
                    })
                    
                    const mArrTemp = []
                    Object.keys(groups).forEach(k => {
                        groups[k].sort((a, b) => b.deliveryDate - a.deliveryDate)
                        const deliveryDateNewestItem = groups[k][0]
                        deliveryDateNewestItem.qty = groups[k].reduce((total, cur) => total + cur.qty, 0)
                        deliveryDateNewestItem.qtyOrigin = deliveryDateNewestItem.qty
                        deliveryDateNewestItem.stockOutNo = groups[k].map(gk => gk.sourceOrder).join(',')
                        mArrTemp.push(deliveryDateNewestItem)
                    })
                    $scope.buyPlan.formInfo.materialList = mArrTemp
                } else if (stockOutType == 2) { // 补库汇总新增
                    $scope.buyPlan.formInfo.headerInfo.typeId = '2';
                    $scope.buyPlan.formInfo.headerInfo.typeDesc = '补库';
                } else if (stockOutType == 3) { // 紧急汇总新增
                    $scope.buyPlan.formInfo.headerInfo.typeId = '1';
                    $scope.buyPlan.formInfo.headerInfo.typeDesc = '紧急';
                }
                $scope.changeTab(2);
            };

            $scope.prevStep = function () {
                $scope.buyPlan.formInfo.materialList = [];
                switch($scope.buyPlan.formInfo.headerInfo.stockOutFlag) {
                    case 0:
                        getMaterielList(1);
                        $scope.changeTab(1);
                        break;
                    case 1:
                        getMaterielListLack(1);
                        $scope.changeTab(5);
                        break;
                    case 2:
                        getMaterielAllListLack(1);
                        $scope.changeTab(6);
                        break;
                    case 3:
                        getMaterielAllListLack(1);
                        $scope.changeTab(7);
                        break;
                }
            };

            $scope.saveAuditPlan = function (type, id, message) {
                var service = "device",
                    reqUrl = "/buyPlan/audit",
                    param = {
                        id: id,
                        auditNote: message
                    };
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    param.auditStatus = 2;
                } else {
                    param.auditStatus = 1;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.buyPlan.formInfo.headerInfo.auditNote = "";
                });
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.materiels = {
                datePickerFlag: [false, false],
                markInfo: {
                    allCheckedBill: false,
                    curRow: -1
                },
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                condition: {},
                dataList: [],
                tableConfig: { // 新增
                    fixedWidth: 40,
                    scrollWidth: 1600,
                    tableCol: [
                        {
                            type: "",
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "单位",
                            dataField: "unit",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "采购组",
                            dataField: "purchaseGroup",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "出库频次",
                            dataField: "salesRate",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "单价",
                            dataField: "price",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "库存上限",
                            dataField: "maxSafeAmount",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "实时库存",
                            dataField: "nowAmount",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "在途数量",
                            dataField: "onWayAmount",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "需求数量（月度）",
                            dataField: "monthAmount",
                            width: 140,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "需求数量（紧急）",
                            dataField: "urgentAmount",
                            width: 140,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "计划数量",
                            dataField: "planAmount",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "可替换零件编号",
                            dataField: "replaceMaterialsNo",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "可替换零件中文名",
                            dataField: "replaceMaterialsDes",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "可替换零件库存",
                            dataField: "replaceInventory",
                            width: 130,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        }
                    ]
                },
                setFixedWidth: function () {
                    $scope.materiels.tbStyle = {
                        billFixedWidth: {
                            left: $scope.materiels.tableConfig.fixedWidth + "px"
                        },
                    }
                },
                search: function (curpage) {
                    getMaterielList(curpage);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewDetail":
                            viewDetail(item);
                            break;
                        case "viewSapError":
                            viewSapError(item);
                            break;
                        case "downloadAttach":
                            downloadAttach(item);
                            break;
                        default:
                            break;
                    }
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                reset: function () {
                    $scope.materiels.condition = {};
                    $scope.materiels.condition.monthRequire = false;
                    $scope.materiels.condition.urgentRequire = false;
                },
                switchDatePicker: function (index) {
                    $scope.materiels.datePickerFlag = [false, false];
                    if (angular.isDefined(index)) {
                        $scope.materiels.datePickerFlag[index] = true;
                    }
                },
                checkDate: function (obj, startFiled, endFiled) {
                    var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                    if (!!timeFormatObj.tStart) {
                        obj[startFiled] = timeFormatObj.tStart;
                    }
                    if (!!timeFormatObj.tEnd) {
                        obj[endFiled] = timeFormatObj.tEnd;
                    }
                },
                selectRow: function (index) {
                    $scope.materiels.markInfo.cueRow = index
                },
                selectAll: function (list, type) {
                    angular.forEach(list, function (item) {
                        item.isChecked = $scope.materiels.markInfo["allChecked" + type];
                        asyncToSelected(item);
                    });
                },
                selectSingle: function (item, list, type) {
                    if (!item.isChecked) {
                        $scope.materiels.markInfo["allChecked" + type] = false;
                    } else {
                        if (!checkAll(list)) {
                            $scope.materiels.markInfo["allChecked" + type] = false;
                        } else {
                            $scope.materiels.markInfo["allChecked" + type] = true;
                        }
                    }
                    asyncToSelected(item);
                },
            };

            $scope.importPlan = function () {
                var param = {
                    name: "采购计划",
                    templateReqService: "device",
                    templateReqUrl: "/buyPlan/downloadBuyPlan",
                    importReqService: "device",
                    importReqUrl: "/buyPlan/importBuyPlan",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };


            $scope.buyPlan = {
                submitted: false,
                formInfo: {
                    headerInfo: {},
                    materialList: []
                },
                tableConfig: { // 编辑，审核，详情
                    scrollWidth: 1100,
                    tableCol: [
                        {
                            name: "零件编号",
                            width: 150,
                            dataField: "materialsNo",
                            needInput: false
                        },
                        {
                            name: "零件中文名",
                            width: 150,
                            dataField: "materialsDes",
                            needInput: false
                        },
                        {
                            name: "零件分类",
                            width: 120,
                            dataField: "materialsType",
                            needInput: false
                        },
                        {
                            name: "零件单位",
                            width: 120,
                            dataField: "unit",
                            needInput: false
                        },
                        {
                            name: "采购组",
                            width: 120,
                            dataField: "purchaseGroup",
                            needInput: false
                        },
                        {
                            name: "供货商名称",
                            width: 100,
                            dataField: "supplierName",
                            needInput: true,
                            inputType: "supplierName"
                        },
                        {
                            name: "替换零件编号",
                            width: 120,
                            dataField: "replaceMaterialsNo",
                            needInput: false
                        },
                        {
                            name: "替换零件中文名",
                            width: 120,
                            dataField: "replaceMaterialsDes",
                            needInput: false
                        },
                        {
                            name: "单价(￥)",
                            width: 100,
                            dataField: "price",
                            needInput: false,
                            inputType: "price"
                        },
                        {
                            name: "数量",
                            width: 100,
                            dataField: "qty",
                            needInput: true,
                            inputType: "qty"
                        },
                        {
                            name: "交货日期",
                            width: 140,
                            dataField: "deliveryDateShow",
                        },
                        {
                            name: "备注",
                            width: 100,
                            dataField: "remark",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "是否创建采购单",
                            width: 120,
                            dataField: "isGenerateShow",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "审批状态",
                            width: 120,
                            dataField: "stockAddStateShow",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "驳回原因",
                            width: 120,
                            dataField: "stockAppRemark",
                            needInput: false,
                            inputType: ""
                        },
                        {
                            name: "驳回时间",
                            width: 140,
                            dataField: "stockAddRejectTimeShow",
                            needInput: false,
                            inputType: ""
                        },
                    ]
                },
                delMateriel: function (index) {
                    ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                        $scope.buyPlan.formInfo.materialList.splice(index, 1);
                    });
                },
                saveData: function (invalid) {
                    if (!invalid) {
                        $scope.buyPlan.submitted = true;
                        return;
                    }

                    if (!$scope.buyPlan.formInfo.materialList || $scope.buyPlan.formInfo.materialList.length === 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }

                    let errorCount = 0;
                    for (const item of $scope.buyPlan.formInfo.materialList) {
                        if ($scope.checkQty(item)) {
                            errorCount++;
                        }
                    }
                    if (errorCount > 0) {
                        return;
                    }

                    var reqUrl = $scope.tabFlag.type === 1 ? "/buyPlan/add" : "/buyPlan/update";

                    var param = angular.copy($scope.buyPlan.formInfo);

                    ybHttp.Post('device', reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        if (Array.isArray(resp.value) && resp.value.length > 0) {
                            var msg = `所选缺货单据号失败 ${resp.value.length} 条，失败原因：<div class='abnormal-msg'>${resp.value.join('<br/>')}</div>`
                            ybWidget.ShowMessage(msg, MESG_TYPE.Warn, {isHtml: true}).then(function () {
                                afterSaveData();
                            });
                        } else {
                            ybWidget.ShowToaster('success', '操作成功');
                            afterSaveData();
                        }
                    });

                    function afterSaveData() {
                        if ($scope.tabFlag.type === 0) {
                            getDataList(1);
                        } else {
                            getDataList();
                        }
                        $scope.changeTab(0);
                    }
                }
            };

            $scope.checkQty = function(item) {
                item.qtyShowErr = false;
                item.qtyErr = false;
                item.qtyErrLack = false;

                if (!item.qty || item.qty == 0) {
                    item.qtyShowErr = true;
                    item.qtyErr = true;
                } else if ($scope.buyPlan.formInfo.headerInfo.stockOutFlag == 1 && item.qty < item.qtyOrigin) {
                    item.qtyShowErr = true;
                    item.qtyErrLack = true;
                }
                return item.qtyErr || item.qtyErrLack
            };

            $scope.showErrTip = function (item) {
                if (item.qtyErr||item.qtyErrLack) {
                    item.qtyShowErr = true
                }
            };

            $scope.hideErrTip = function (item) {
                item.qtyShowErr = false
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.buyPlan.formInfo = {
                    headerInfo: {},
                    materialList: []
                };
                $scope.materiels.condition.monthRequire = false;
                $scope.materiels.condition.urgentRequire = false;
            }

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.buyPlan.formInfo = data;
                    $scope.changeTab(4);
                });
            }

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/buyPlan/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (resp.value && resp.value.materialList && resp.value.materialList.length > 0) {
                        angular.forEach(resp.value.materialList, function(item){
                            item.deliveryDateShow = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');
                            item.stockAddStateShow = $filter("ProgressStatus")(item.stockAddState, 'stockAddStatus');
                            item.isGenerateShow = $filter("ProgressStatus")(item.isGenerate, 'generateState');
                            item.stockAddRejectTimeShow = $filter("YbDate")(item.stockAddRejectTime, 'yyyy-MM-dd');
                        })
                    }
                    return resp.value;
                });
            }


            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/buyPlan/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.sendStatusShow = $filter("ProgressStatus")(item.sendStatus, "sendState");
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getMaterielList(curPage) {
                $scope.materiels.markInfo = {
                    allCheckedBill: false,
                    curRow: -1
                };

                if (!!curPage) {
                    $scope.materiels.pageInfo.curPage = curPage;
                }
                const filtersT = angular.copy($scope.materiels.condition);
                filtersT.monthRequire = filtersT.monthRequire ? 1 : 0;
                filtersT.urgentRequire = filtersT.urgentRequire ? 1 : 0;

                var param = {
                    pageSize: $scope.materiels.pageInfo.pageSize,
                    pageNum: $scope.materiels.pageInfo.curPage,
                    filters: filtersT
                };
                ybHttp.Post("device", "/buyPlan/reportList", param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        checkSelectMaterial(item);
                    });
                    $scope.materiels.markInfo.allCheckedBill = checkAll(resp.value.list);
                    $scope.materiels.pageInfo.totalRows = resp.value.total;
                    $scope.materiels.pageInfo.totalPages = resp.value.pages;
                    $scope.materiels.dataList = resp.value.list;
                });
            }

            function checkSelectMaterial(material) {
                var isNeedCheck = false;
                if (findIndexFromSelected(material) > -1) {
                    isNeedCheck = true;
                }
                material.isChecked = isNeedCheck;
            }

            function asyncToSelected(material) {
                if (material.isChecked) {
                    pushToSelected(material);
                    return;
                }
                removeFromSelected(material);
            }

            function pushToSelected(material) {
                if (findIndexFromSelected(material) === -1) {
                    $scope.buyPlan.formInfo.materialList.push({
                        materialsDes: material.materialsDes,
                        materialsNo: material.materialsNo,
                        materialsType: material.materialsType,
                        unit: material.unit,
                        price: material.price,
                        qty: material.planAmount || material.planNum,
                        sourceOrder: material.billNo,
                        purchaseGroup: material.purchaseGroup,
                        replaceMaterialsNo: material.replaceMaterialsNo,
                        replaceMaterialsDes: material.replaceMaterialsDes,
                        salesRate: material.salesRate,
                        deliverySpend: material.deliverySpend,
                        deliveryDateShow: material.deliveryDateShow,
                        deliveryDate: material.deliveryDate,
                        remark: material.remark,
                    });
                }
            }

            function removeFromSelected(material) {
                var index = findIndexFromSelected(material);
                if (index > -1) {
                    $scope.buyPlan.formInfo.materialList.splice(index, 1);
                }
            }

            function findIndexFromSelected(material) {
                var index = -1;
                for (var i = 0; i < $scope.buyPlan.formInfo.materialList.length; i++) {
                    var selectedItem = $scope.buyPlan.formInfo.materialList[i];
                    if (material.billNo === selectedItem.sourceOrder && material.materialsNo === selectedItem.materialsNo) {
                        index = i;
                        break;
                    }
                }
                return index;
            }

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/buyPlan/download",
                    importReqService: "device",
                    importReqUrl: "/buyPlan/import",
                    importErrorUrl: ""
                };

                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    angular.forEach(data, function (item) {
                        var flag = true;
                        angular.forEach($scope.buyPlan.formInfo.materialList, function (data) {
                            if (item.materialsNo === data.materialsNo) {
                                data.qty = item.planAmount;
                                flag = false;
                            }
                        });
                        if (flag) {
                            item.qty = item.planAmount;
                            $scope.buyPlan.formInfo.materialList.push(item);
                        }
                    });
                });
            };




            $scope.lackTableConfig = {
                fixedWidth: 40,
                scrollWidth: 1800,
                tableCol: [
                    {
                        name: "交付日期",
                        dataField: "deliveryDateShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "交付说明",
                        dataField: "lackRemark",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户编号",
                        dataField: "dealerCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "客户名称",
                        dataField: "dealerName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据编号",
                        dataField: "billNo",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据类型",
                        dataField: "billType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购级别",
                        dataField: "purchaseLevelName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购员",
                        dataField: "purchaseUser",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "调度员",
                        dataField: "planUser",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "出库类型",
                        dataField: "outType",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "创建时间",
                        dataField: "createTimeShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购组",
                        dataField: "purchaseGroup",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单价",
                        dataField: "price",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "需求数量",
                        dataField: "needQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "未分发数量",
                        dataField: "notInformQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "总库存",
                        dataField: "allInventory",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "计划外仓库库存",
                        dataField: "outInventory",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "计划内仓库库存",
                        dataField: "inInventory",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "缺货数量",
                        dataField: "lackNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    }
                ]
            };
            $scope.lackCollectTableConfig = {
                fixedWidth: 40,
                scrollWidth: 1800,
                tableCol: [
                    {
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "供货商代码",
                        dataField: "supplierVlt",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "供货商名称",
                        dataField: "supplierVltName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购组",
                        dataField: "purchaseGroup",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单价",
                        dataField: "price",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "缺货数量",
                        dataField: "lackNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "可用库存数量",
                        dataField: "enableNum",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "未清采购订单数量",
                        dataField: "unableNum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "库存上限",
                        dataField: "safeNum",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "补货量",
                        dataField: "planNum",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "补货金额",
                        dataField: "totalMoney",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "滞销数量",
                        dataField: "unsalableNum",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                    },
                ]
            };
            $scope.setFixedWidthLack = function () {
                $scope.tbStyleLack = {
                    billFixedWidth: {
                        left: $scope.lackTableConfig.fixedWidth + "px"
                    },
                }
            };

            $scope.markInfoLack = {
                allCheckedBill: false,
                curRow: -1
            };
            $scope.markAllInfoLack = {
                allCheckedBill: false,
                curRow: -1
            };
            $scope.selectRowLack = function (index) {
                $scope.markInfoLack.curRow = index
            };

            $scope.selectAllLack = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfoLack["allChecked" + type];
                    asyncToSelected(item);
                });
            };

            $scope.selectSingleLack = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfoLack["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfoLack["allChecked" + type] = false;
                    } else {
                        $scope.markInfoLack["allChecked" + type] = true;
                    }
                }
                asyncToSelected(item);
            };

            $scope.pageInfoLack = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.pageAllInfoLack = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };            
            $scope.conditionLack = {};
            $scope.conditionLackAll = {};
            $scope.resetLack = function () {
                $scope.conditionLack = {};
            };
            $scope.dataListLack = [];
            $scope.dataListLackAll = [];

            $scope.searchLack = function (curpage) {
                getMaterielListLack(curpage);
            };
            $scope.searchLackAll = function (curpage) {
                getMaterielAllListLack(curpage);
            };
            function getMaterielListLack(curPage) {
                $scope.markInfoLack = {
                    allCheckedBill: false,
                    curRow: -1
                };

                if (!!curPage) {
                    $scope.pageInfoLack.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfoLack.pageSize,
                    pageNum: $scope.pageInfoLack.curPage,
                    filters: angular.copy($scope.conditionLack),
                    isLack: $scope.isWJ ? '1' : undefined
                };
                if ($scope.isWJ) {
                    param.filters.isLack = 1
                }else {
                    param.filters.isLack = undefined
                }
                ybHttp.Post("device", "/report/materialStorage", param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.planAmount = Math.abs(item.lackNum||0);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createTimeShow = $filter("YbDate")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        item.isChecked = false;
                    });
                    $scope.markInfoLack.allCheckedBill = checkAll(resp.value.list);
                    $scope.pageInfoLack.totalRows = resp.value.total;
                    $scope.pageInfoLack.totalPages = resp.value.pages;
                    $scope.dataListLack = resp.value.list;
                });
            }
            function getMaterielAllListLack(curPage) {
                $scope.markAllInfoLack = {
                    allCheckedBill: false,
                    curRow: -1
                };

                if (!!curPage) {
                    $scope.pageAllInfoLack.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageAllInfoLack.pageSize,
                    pageNum: $scope.pageAllInfoLack.curPage,
                    filters: angular.copy($scope.conditionLackAll),
                };
                ybHttp.Post("device", $scope.curUrl4AllListLack, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                    });
                    $scope.dataListLackAll = resp.value.list;
                    $scope.markAllInfoLack.allCheckedBill = checkAll(resp.value.list);

                    $scope.pageAllInfoLack.totalRows = resp.value.total;
                    $scope.pageAllInfoLack.totalPages = resp.value.pages;
                });
            }
            $scope.selectStockOuter = function () {
                var param = {
                    name: "采购员",
                    type: "businessStaff"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.buyPlan.formInfo.headerInfo.stockOuterName = data.name;
                    $scope.buyPlan.formInfo.headerInfo.stockOuter = data.userId;
                });
            };

            $scope.rejectInfo = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                dataList: [],
                condition: {},
                search: function (curPage) {
                    getRejectDataList(curPage);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewDetail":
                            var param = {
                                id: item.id
                            };
                            ybHttp.Get('device', '/buyPlan/itemRejectSum', param).then(function (resp) {
                                if (resp.code !== 0) {
                                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                    return;
                                }
                                if (resp.value && resp.value.materialList && resp.value.materialList.length > 0) {
                                    angular.forEach(resp.value.materialList, function(item){
                                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');
                                        item.stockAddStateShow = $filter("ProgressStatus")(item.stockAddState, 'stockAddStatus');
                                        item.isGenerateShow = $filter("ProgressStatus")(item.isGenerate, 'generateState');
                                        item.stockAddRejectTimeShow = $filter("YbDate")(item.stockAddRejectTime, 'yyyy-MM-dd');
                                    })
                                }
                                $scope.buyPlan.formInfo = resp.value || {};
                                $scope.changeTab(9);
                            });
                            break;
                        default:
                            break;
                    }
                },
                tableConfig: {
                    tableCol: [
                        {
                            name: "采购计划单号",
                            dataField: "planOrder",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            clickFn: "viewDetail",
                        },
                        {
                            name: "申请人",
                            dataField: "createName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "申请部门",
                            dataField: "deptName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "采购方式",
                            dataField: "purchaseType",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "备注",
                            dataField: "note",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核人",
                            dataField: "auditName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核时间",
                            dataField: "auditDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核状态",
                            dataField: "auditStatusShow",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "审核意见",
                            dataField: "auditNote",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                        {
                            name: "创建采购单状态",
                            dataField: "sendStatusShow",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                        },
                    ]
                },
            };

            function getRejectDataList(curPage) {
                $scope.exportParam.sectionParam.rejectSumIds = [];

                var service = "device";
                var reqUrl = "/buyPlan/rejectSum";
                
                if (!!curPage) {
                    $scope.rejectInfo.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.rejectInfo.pageInfo.pageSize,
                    pageNum: $scope.rejectInfo.pageInfo.curPage,
                    filters: angular.copy($scope.rejectInfo.condition)
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.sendStatusShow = $filter("ProgressStatus")(item.sendStatus, "sendState");
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                    });
                    $scope.rejectInfo.pageInfo.totalRows = resp.value.total;
                    $scope.rejectInfo.pageInfo.totalPages = resp.value.pages;
                    $scope.rejectInfo.dataList = resp.value.list;
                });
            }
            $scope.rejectSummary = function () {
                $scope.rejectInfo.pageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                }
                $scope.rejectInfo.dataList = [];
                $scope.rejectInfo.condition = {};
                getRejectDataList(1).then(() => {
                    $scope.changeTab(8);
                })
            };

            function getRejectSumBillIds() {
                $scope.exportParam.sectionParam.rejectSumIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.rejectSumIds.push(item.id);
                    }
                });
            }

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);